package com.lw.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lw.ssm.cache.ScoreCache;
import com.lw.ssm.event.ScoreEvent;
import com.lw.ssm.exceptions.MyBaseException;
import com.lw.ssm.mapper.ScoreMapper;
import com.lw.ssm.pojo.Score;
import com.lw.ssm.service.ScoreService;
import com.lw.ssm.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/12 10:53
 */
@Service
@Transactional
public class ScoreServiceImpl implements ScoreService {

    private ScoreMapper scoreMapper;

    private ScoreCache scoreCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setScoreCache(ScoreCache scoreCache) {
        this.scoreCache = scoreCache;
    }

    @Autowired
    public void setScoreMapper(ScoreMapper scoreMapper) {
        this.scoreMapper = scoreMapper;
    }

    @Override
    public List<Score> findById(Long stuId) {

        return scoreMapper.findById(stuId);
    }

    @Override
    public PageInfo<Score> findAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Score> allData = scoreCache.getAllData();
        List<Score> scoreList = allData.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<Score> pageInfo = new PageInfo<>(scoreList);
        pageInfo.setTotal(allData.size());
        return pageInfo;
    }

    @Override
    public void addScore(Score score) {
        Assert.isTrue(!score.isEmpty(),()->{
            throw new MyBaseException("数据不能为空", ResultCode.DATA_EMPTY);
        });
        scoreMapper.addScore(score);
        context.publishEvent(new ScoreEvent());
    }

    @Override
    public void updateScore(Score score) {
        scoreMapper.updateScoreById(score);
        context.publishEvent(new ScoreEvent());
    }

    @Override
    public void deleteScore(Long id) {
        scoreMapper.deleteScore(id);
        context.publishEvent(new ScoreEvent());
    }
}
